<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-permisaction="['user:generaluser:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="generaluserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="头像" align="center" prop="avatar" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-avatar :size="50" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
      <el-table-column
        label="手机"
        align="center"
        prop="phone"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="身份"
        align="center"
        prop="familyRelationship"
        width="100"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="主账号"
        align="center"
        prop="isFamilyOwner"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="会员等级" align="center" prop="userLevel" :show-overflow-tooltip="true" />
      <el-table-column label="积分" align="center" prop="integral" :show-overflow-tooltip="true" />
      <el-table-column
        label="VIP有效期"
        align="center"
        prop="vipDeadlineTime"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'status','状态')"
          />
        </template>
      </el-table-column>
      <el-table-column label="禁言" align="center" prop="isBanned" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isBanned"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'isBanned','禁言')"
          />
        </template>
      </el-table-column>

      <el-table-column label="用户分组" align="center" prop="groupId" :show-overflow-tooltip="true" />
      <el-table-column label="用户类型" align="center" prop="userType" :show-overflow-tooltip="true" />
      <el-table-column label="用户备注" align="center" prop="mark" :show-overflow-tooltip="true" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permisaction="['user:generaluser:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>

          <el-button
            v-permisaction="['user:generaluser:VIP']"
            size="mini"
            type="text"
            @click="handleVIP(scope.row)"
          >充值记录</el-button>
          <el-button
            v-permisaction="['user:generaluser:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body style="align-items:flex-start">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户头像" prop="avatar">
          <el-avatar :size="80" :src="form.avatar"></el-avatar>
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="用户昵称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="手机号码" />
        </el-form-item>
        <el-form-item label="身份" prop="familyRelationship">
          <el-radio-group v-model="form.familyRelationship">
            <el-radio
              v-for="(item,index) in relationshipOptions "
              :key="index"
              :label="Number(item.dictValue)"
            >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="会员等级" prop="userLevel">
          <el-radio-group v-model="form.userLevel">
            <el-radio
              v-for="(item) in userLevelOptions "
              :key="item.dictValue"
              :label="item.dictValue"
            >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户分组" prop="groupId">
          <el-input v-model="form.groupId" placeholder="用户分组id" />
        </el-form-item>
        <el-form-item label="剩余积分" prop="integral">
          <el-input-number
            v-model="form.integral"
            :precision="2"
            :step="0.1"
            :min="0"
            label="用户剩余积分"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="可邀请数" prop="invitationCount">
          <el-input-number v-model="form.invitationCount" :min="0" label="剩余可邀请数"></el-input-number>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="(item,index) in sexOptions "
              :key="index"
              :label="Number(item.dictValue)"
            >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio
              v-for="(item,index) in usertypeOptions "
              :key="index"
              :label="Number(item.dictValue)"
            >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="VIP有效期" prop="vipDeadlineTime">
          <el-date-picker
            v-model="form.vipDeadlineTime"
            type="date"
            placeholder="VIP有效期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            :readonly="true"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="主账号" prop="isFamilyOwner">
          <el-switch v-model="form.isFamilyOwner" active-value="T" inactive-value="F"></el-switch>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="T" inactive-value="F"></el-switch>
        </el-form-item>
        <el-form-item label="禁言" prop="isBanned">
          <el-switch v-model="form.isBanned" active-value="T" inactive-value="F"></el-switch>
        </el-form-item>
        <el-form-item label="家庭码" prop="familyCode">
          <el-input v-model="form.familyCode" placeholder="家庭码" />
        </el-form-item>
        <el-form-item label="用户备注" prop="mark">
          <el-input
            ype="textarea"
            v-model="form.mark"
            placeholder="用户备注"
            maxlength="200"
            show-word-limit
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openVIP" width="800px">
      <VIPDeadLineList :userId="userId" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listgeneralUser,
  getgeneralUser,
  delgeneralUser,
  addgeneralUser,
  updategeneralUser,
} from "@/api/generaluser";

//充值记录
import VIPDeadLineList from "@/components/Myuser/vipDeadLine";

export default {
  name: "FamilyMember",
  props: {
    familyCode: {
      type: String,
      default: "",
    },
  },
  components: {
    VIPDeadLineList,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        familyCode: undefined,
        familyRelationship: undefined,
        groupId: undefined,
        isBanned: undefined,
        isFamilyOwner: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        avatar: [{ required: true, message: "头像不能为空", trigger: "blur" }],
        nickname: [
          {
            required: true,
            message: "用户昵称不能为空",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
        ],
        familyRelationship: [
          {
            required: true,
            message: "身份不能为空",
            trigger: "blur",
          },
        ],
      },
      generaluserList: [], //列表
      sexOptions: [], //性别选项
      relationshipOptions: [], //家庭身份
      usertypeOptions: [], //用户类型
      boolOptions: [], //是否
      userLevelOptions: [], //会员级别

      //vip 充值记录组件
      openVIP: false,
      userId: undefined,
      //家庭成员
      open_FamilyMember: false,
      familyCode: undefined,
    };
  },
  created() {
    this.queryParams.familyCode = this.familyCode
    this.getList();
    this.sexOptions = this.$store.getters.parameter.sys_user_sex;
    this.relationshipOptions = this.$store.getters.parameter.sys_family_relationship;
    this.usertypeOptions = this.$store.getters.parameter.general_user_type;
    this.boolOptions = this.$store.getters.parameter.sys_bool;
    this.userLevelOptions = this.$store.getters.parameter.general_user_level;
  },
   watch: {
    //监听子控件内容的改动,发送给父级组件
    familyCode: {
      handler(newValue, oldValue) {
        this.queryParams.familyCode = this.familyCode; 
        this.getList();
      },
      deep: true,
    },
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listgeneralUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          // console.log(response)
          this.generaluserList = response.data.list;
          this.total = response.data.count;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        avatar: undefined,
        familyCode: undefined,
        familyRelationship: undefined,
        groupId: undefined,
        integral: undefined,
        invitationCount: undefined,
        isBanned: undefined,
        isFamilyOwner: undefined,
        isPromoter: undefined,
        lastIp: undefined,
        lastTime: undefined,
        level: undefined,
        loginType: undefined,
        mark: undefined,
        nickname: undefined,
        payCount: undefined,
        phone: undefined,
        sex: undefined,
        signNum: undefined,
        spreadCount: undefined,
        spreadTime: undefined,
        spreadUid: undefined,
        status: undefined,
        userId: undefined,
        userType: undefined,
        vipDeadlineTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小程序用户表";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getgeneralUser(userId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 查看家人按钮操作 */
    handleFamily(row) {
      console.log(row.familyCode);
      this.familyCode = row.familyCode;
      this.open_FamilyMember = true;
      this.title = row.nickname + "的家庭成员";
    },
    /** 充值结论按钮操作 */
    handleVIP(row) {
      console.log(row);
      this.userId = row.userId;
      this.openVIP = true;
      this.title = row.nickname + "的充值记录";
      // getgeneralUser(userId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改用户";
      // });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId !== undefined) {
            updategeneralUser(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addgeneralUser(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.userId || this.ids;
      this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delgeneralUser(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    // 状态修改
    handleSwitchChange(row, filed, tipStr) {
      const text = row[filed] == "T" ? "启用" : "停用";
      console.log(row[filed]);
      this.$confirm(
        '确认要"' + text + row.nickname + tipStr + '"功能吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          let updateData = {};
          updateData["userId"] = row.userId;
          updateData[filed] = row[filed];
          console.log(updateData);

          updategeneralUser(updateData).then((response) => {
            if (response.code === 200) {
              return true;
            } else {
              this.msgError("修改失败");
              return false;
            }
          });

          // return changeUserStatus(row.userId, row.status)
        })
        .then(() => {
          this.msgSuccess(text + row.nickname + tipStr + "成功");
          // this.getList();
        })
        .catch(function () {
          // row.status = row.status === "0" ? "1" : "0";
        });
    },
  },
};
</script>